/**   
*
* @创建人：Liuyong   
* @创建时间：2013-10-31 下午04:04:10   
*    
*/ 
package com.crmsys.login.controller;

import java.security.interfaces.RSAPublicKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.crmsys.auth_framework.auth.model.CUser;
import com.crmsys.auth_framework.auth.service.IUserInfoService;
import com.crmsys.common.constant.AuthConstants;
import com.crmsys.common.util.SessionUtil;

/**   
 *
 * @描述：   
 * @创建人：Liuyong   
 * @创建时间：2013-10-31 下午04:04:10   
 * @修改人：Liuyong   
 * @修改时间：2013-10-31 下午04:04:10   
 * @修改备注：   
 * @version 1.0
 *    
 */
@Controller
@SessionAttributes(value={AuthConstants.SESSION_USER_INFO})
@RequestMapping(value="/loginController")
public class LoginController {
	@Autowired
	private IUserInfoService iUserInfoService;
	/**
	 * 
	*@param model
	*@param userName
	*@param password
	*@return
	* @描述：   验证用户有效性
	* @创建人：Liuyong   
	* @创建时间：2013-11-7 上午09:30:19   
	* @修改人：Liuyong   
	* @修改时间：2013-11-7 上午09:30:19   
	* @修改备注：   
	* @version 1.0
	*
	 */
	@RequestMapping(value="/validateLogin")
	@ResponseBody
	public Map validateLogin(HttpServletRequest request,ModelMap model,String userName,String password){
		Map map  = new HashMap();
		boolean isExist = false;
		Map<String, String> logininfo = SessionUtil.decryptUsernameAndPasswd(request, userName,password);//解密并获取用户名和密码
		List<CUser> list= iUserInfoService.getUserInfo(logininfo.get("userName"),logininfo.get("password"));//验证登陆
		CUser cuser = new CUser();
		if(!list.isEmpty()&&list.size()==1){
		   isExist = true;
		   cuser = list.get(0);
		}
		if(isExist){
			//存在该用户
			String id = cuser.getId().toString();
			List listRole = iUserInfoService.getUserRole(id);
			if(!listRole.isEmpty()&&listRole.size()>0){
				//绑定了角色
				map.put("flag", "1");
				map.put("listRole", listRole);
				model.put(AuthConstants.SESSION_USER_INFO, cuser);
			}else{
				RSAPublicKey pk = SessionUtil.genRandom(request);
				map.put("random_pe", pk.getPublicExponent().toString(16));
				map.put("random_pk", pk.getModulus().toString(16));
				map.put("flag", "0");
				map.put("mes", "用户未绑定角色。");
			}
		}else{
			RSAPublicKey pk = SessionUtil.genRandom(request);
			map.put("random_pe", pk.getPublicExponent().toString(16));
			map.put("random_pk", pk.getModulus().toString(16));
			map.put("flag", "0");
			map.put("mes", "用户不存在，请重新登陆");
		}
		return map;
	}
	
}
